var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');
var async = require('async');


var YjxPptUserPageModel = function (obj) {
    YjxBaseModel.call(this,obj);

    // `addr_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '地址id',
    // `base_id` bigint(20) NOT NULL COMMENT '拷贝源地址id',
    // `addr_type` int(3) NOT NULL DEFAULT '0' COMMENT '地址类型：0用户地址管理, 1用户地址列表用, 10商品订单, 20发票订单',
    // `mobile` bigint(20) NOT NULL COMMENT '手机号',
    // `phone` bigint(20) DEFAULT NULL COMMENT '座机号',
    // `name` varchar(20) NOT NULL COMMENT '收货者',
    // `prov` bigint(20) DEFAULT NULL COMMENT '省会',
    // `city` bigint(20) DEFAULT NULL COMMENT '城市',
    // `dist` bigint(20) DEFAULT NULL COMMENT '区',
    // `detail` varchar(500) NOT NULL DEFAULT '' COMMENT '详细地址',
    // `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
    // `default` int(1) NOT NULL DEFAULT '0' COMMENT '默认地址: 0否,1是',
    // `create_time` datetime NOT NULL,
    // `update_time` datetime NOT NULL,
    // `del_flg` int(1) NOT NULL DEFAULT '0',
    // PRIMARY KEY (`addr_id`),
    // KEY `Addr_idx_01` (`user_id`)

};

YjxPptUserPageModel.prototype = new YjxBaseModel();

// 取得表名
YjxPptUserPageModel.prototype.getTableName = function(){
    return 'yjx_ppt_user_page';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxPptUserPageModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'page_id='+this.page_id;
};


/**
 * 根据文档id逻辑删除对应pages
 *
 * @author 王俊
 * @date 2017-11-17
 *
 * @param callback
 *          err: 操作是否成功
 *
 * 注意:
 * 1. 复制自 mysql/mapping ItbPageModel.prototype.deletePagesByDocIdLogic 方法
 * 2. 调用此方法的模型需存在: update_by doc_id 等属性
 */
YjxPptUserPageModel.prototype.deletePagesByDocIdLogic = function(callback){
    var THIS = this;
    var tableName = this.getDBName() + '.' + this.getTableName();
    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE '+tableName+' SET del_flg=1, update_time=sysdate(), update_by=? WHERE doc_id=? AND del_flg=0 ';
        var sqlValue = [THIS.update_by, THIS.doc_id];
        sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};


/**
 * 查询指定文档的page信息及其来源模版的replace信息
 *
 * @author 王俊
 * @date 2017-11-18
 *
 * @param callback 回调
 *          err: 错误原因
 *
 * 注意:
 * 1. 复制自 mysql/mapping ItbPageModel.prototype.getPageInfoAndTmplRep
 * 2. 调用此方法的模型需存在 以下属性
 *      tmpl_id: 模板 id
 *      doc_id: 文档 id
 *      page_id: 文档页id
 */

YjxPptUserPageModel.prototype.getPageInfoAndTmplRep=function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxPptUserPageModel.getPageInfoAndTmplRep Err:'+err);
        }
        // Use the connection
        var sql = ' SELECT t.*, t2.page_id AS tmpl_page_id, t2.replaces AS tmpl_replaces, t2.thumb_s AS tmpl_thumb ' +
            ' FROM yjx.yjx_ppt_user_page t ' +
            ' LEFT JOIN itbour.itb_tmpl_page t2 ' +
            ' ON t.base_page_id = t2.page_id AND t2.del_flg = 0 ';
        if (THIS.tmpl_id) {
            sql += ' AND t2.tmpl_id = ' + THIS.tmpl_id;
        }
        sql +=  ' WHERE t.del_flg = 0 ';
        if (THIS.doc_id) {
            sql += ' AND t.doc_id = ' + THIS.doc_id;
        }
        if (THIS.page_id) {
            sql += ' AND t.page_id = ' + THIS.page_id;
        }
        sql += ' ORDER BY t.page_index ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error, result);
        });
    });
};


/**
 * 创建/更新 ppt 作品页
 *
 * @author 王俊
 * @date 2017-11-19
 *
 * @param callback  回调
 * @param doc_id    ppt 作品唯一标识
 * @param user_type 用户类型
 * @param update_by 更新者
 * @param arrPageJson
 *          pages:[{
 *              page_id: 1, // 为空或<=0时新规,大于0时更新
 *              base_page_id: 1,
 *              thumb: BASE_IP + '/images/page01.png',
 *              page_index: 0,
 *              content: []
 *          }]
 *
 * 注意:
 * 1. 复制自 ItbPageModel.prototype.updatePages 具体逻辑待测
 */
YjxPptUserPageModel.prototype.updatePages = function(callback,doc_id,user_type,update_by,arrPageJson){
    var asyncFuncs = [];
    for (var i in arrPageJson) {

        asyncFuncs.push((function (index, pageJson) {
            return function (asyncCallback) {
                if (Number(pageJson.page_id || '0') <= 0) {
                    // 新规
                    var entity = new YjxPptUserPageModel({
                        doc_id: doc_id,
                        user_type: user_type,
                        update_by: update_by,
                        replaces: JSON.stringify(pageJson.content),
                        page_index: pageJson.page_index,
                        base_page_id: pageJson.base_page_id,
                        dirty: Number(pageJson.dirty || "0")
                        //thumb_s:"xxx" // TODO
                    });
                    entity.saveToDB(function(error, newId){
                        if(error){
                            console.log('YjxPptUserPageModel.js [updatePages] saveToDB error: '+error);
                        }
                        var ret = {page_index: pageJson.page_index, page_id: newId};
                        asyncCallback(null, ret);
                    });
                } else {
                    // 更新
                    var updEnt = new YjxPptUserPageModel({
                        page_id: pageJson.page_id,
                        //doc_id: doc_id,
                        user_type: user_type,
                        update_by: update_by,
                        replaces: JSON.stringify(pageJson.content),
                        page_index: pageJson.page_index,
                        //base_page_id: pageJson.base_page_id,
                        dirty: Number(pageJson.dirty || "0"),
                        del_flg: 0,// 更新时恢复删除状态
                        thumb_s:''// 更新为空,以便图片服务器重新生成
                    });
                    updEnt.updateToDB(function(error2, ret){
                        if(error2){
                            console.log('YjxPptUserPageModel.js [updatePages] updateToDB error: '+error2);
                        }
                        var ret = {page_index: pageJson.page_index, page_id: pageJson.page_id};
                        asyncCallback(null, ret);
                    });
                }
            }
        })(i, arrPageJson[i])); // 利用闭包解决动态参数传递问题
    }
    async.parallel(asyncFuncs, function (err, results) {
        var ret = results.sort(function(a,b){
            return a.page_index - b.page_index;
        });
        var retIds = [];
        for (var i in ret){
            retIds.push(ret[i].page_id);
        }
        callback(err, retIds);
    });
};

/**
 * 根据文档id逻辑删除对应pages
 *
 * @author 王俊
 * @date 2017-11-19
 *
 * @param callback 回调
 *          err: 删除是否成功
 *
 * 注意:
 * 1. 拷贝至 ItbPageModel.prototype.deletePagesByDocIdLogic 具体逻辑待测
 *
 */
YjxPptUserPageModel.prototype.deletePagesByDocIdLogic = function(callback){
    var THIS = this;
    var tableName = this.getDBName() + '.' + this.getTableName();
    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE '+tableName+' SET del_flg=1, update_time=sysdate(), update_by=? WHERE doc_id=? AND del_flg=0 ';
        var sqlValue = [THIS.update_by, THIS.doc_id];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error);
        });
    });
};

/**
 *
 *
 * @author 王俊
 * @date 2017-11-20
 *
 * @param callback
 *          error:错误,null表示无错误
 *          pageModels:页面数据数组,每个元素为： ItbPageModel结构
 *
 * 注意:
 * 1. 复制自 ItbPageModel.js ItbPageModel.prototype.getPagesInfoByDocIds 具体功能待测
 * 2. 调用此方法的数据模型需存在 doc_ids 属性, 根据文档id(多个时逗号连接)获取pages信息
 *
 */
YjxPptUserPageModel.prototype.getPagesInfoByDocIds = function(callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxPptUserPageModel.getPagesInfoByDocIds Err:'+err);
        }
        // Use the connection
        var sql = 'SELECT * FROM yjx.yjx_ppt_user_page t WHERE t.del_flg = 0 AND t.doc_id IN ( ' +
            THIS.doc_ids +
            ' ) ORDER BY t.doc_id, t.page_index ';
        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error, result);
        });
    });
};


/*
 * 参数:user_doc_id:
 * 参数:callback:
 *
 *
 *
 *
 * */
/**
 * 查询出“用户文档页”对应的“模版页数据”和“用户可替换数据”
 *
 * @author 王俊
 * @date 2017-11-20
 *
 * @param user_doc_id   用户doc id
 * @param callback  回调，参数
 *          error:错误,null表示无错误
 *          pageModels:页面数据数组,每个元素为：
 *                  ItbPageModel结构
 *                  tmp_page_thumb_s［模版页的缩略图］
 *
 * 注意:
 * 1. 复制自 ItbPageModel.prototype.getUserPagesCombineTemplateByUserDocId 具体功能待测
 */
YjxPptUserPageModel.prototype.getUserPagesCombineTemplateByUserDocId = function(user_doc_id,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbPageModel.getUserPagesCombineTemplateByUserDocId Err:'+err);
        }
        // Use the connection
        var sql =
            ' select p2.`page_id`,p2.`page_index`,p1.data,p2.`replaces`,p1.`thumb_s` as tmp_page_thumb_s '+
            ' from itbour.itb_tmpl_page p1 ,( '+ // itb_page --> itb_tmpl_page TODO
            ' select p.`page_id`,p.`base_page_id`,p.`data`,p.`replaces`,p.`page_index` '+
            ' from yjx.yjx_ppt_user_page p '+
            ' where p.`doc_id`='+user_doc_id+
            ' and p.user_type=1 '+
            ' and p.`del_flg`=0 '+
            ' order by p.`page_index`) p2 '+
            ' where p1.`page_id`=p2.`base_page_id` '+
            ' order by page_index ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            callback(error, result);
        });
    });
};



module.exports = YjxPptUserPageModel;

